package com.ostrich.cloud.ostrichUserService.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSocketsSet = new CopyOnWriteArraySet<>();


    @OnOpen
    public void opOpen(Session session,String token){
        this.session=session;
        webSocketsSet.add(this);
        log.info("webSocket消息 有新的链接总数:{}",webSocketsSet.size());
    }

    @OnClose
    public void onClose(){
        webSocketsSet.remove(this);
        log.info("webSocket链接断开,总数{}",webSocketsSet.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("webSocket收到客户端发送的消息:{}",message);
    }

    public void SendMessage(String message){
        for (WebSocket webSocket:webSocketsSet){
            log.info("webSocket广播消息{}",message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

}
